package com.example.minzhengtong.ui.adapter;

import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;

import java.util.List;

/**
 * @author xiaoyichao
 * @date 2019/11/13
 * @function
 */
public class TabPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> list;
    private String[] titleString;
    private List<String> titleList;

    public TabPagerAdapter(FragmentManager fm, List<Fragment> list, String[] titles) {
        super(fm);
        mFragmentManager = fm;
        this.list = list;
        this.titleString = titles;
    }

    public TabPagerAdapter(FragmentManager fm, List<Fragment> list, List<String> titles) {
        super(fm);
        mFragmentManager = fm;
        this.list = list;
        this.titleList = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (titleString != null && titleString.length != 0) {
            return titleString[position];
        }
        if (titleList != null && !titleList.isEmpty()) {
            return titleList.get(position);
        }
        return "";
    }

    public void setPageTitle(int position, String title) {
        if (titleString != null && titleString.length != 0) {
            if (position >= 0 && position < titleString.length) {
                titleString[position] = title;
                notifyDataSetChanged();
            }
        } else if (titleList != null && !titleList.isEmpty()) {
            if (position >= 0 && position < titleList.size()) {
                titleList.set(position, title);
                notifyDataSetChanged();
            }
        }
    }

    private FragmentTransaction mCurTransaction;

    private FragmentManager mFragmentManager;

    /**
     * 清除缓存fragment
     *
     * @param container ViewPager
     */
    public void clear(ViewGroup container) {
        if (this.mCurTransaction == null) {
            this.mCurTransaction = this.mFragmentManager.beginTransaction();
        }

        for (int i = 0; i < list.size(); i++) {
            long itemId = this.getItemId(i);
            String name = makeFragmentName(container.getId(), itemId);
            Fragment fragment = this.mFragmentManager.findFragmentByTag(name);
            if (fragment != null) {
                //根据ID删除fragment，
                mCurTransaction.remove(fragment);
            }
        }
        mCurTransaction.commitNowAllowingStateLoss();
    }

    /**
     * 父类的该方法是私有的，故重新定义
     *
     * @param viewId
     * @param id
     * @return
     */
    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }
}
